<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>call函数的实现原理</title>
</head>

<body>
    <script type="text/javascript">
        //第一步打印this
        console.log('this', this, this === window) //输出window对象

        const waitFunc = function () {
            console.log("function_this", this)
        }
        waitFunc() //因为是this.xxx或者说window.xx 所以运行函数this指向window
        //douyu函数
        var douyu = function (a, b) {
            console.log("输出ab", a, b)
            console.log("输出name1_2", this.name1, this.name2)
        }
        var huyaObj = {
            name1: '虎牙——a',
            name2: "虎牙——b"
        }
        douyu.call(huyaObj, "虎牙3", "虎牙4")

        const targetObj = {
            name1: "target1号",
            name2: 'target2号',

        }
        //实现这个Function函数的call功能
        Function.prototype.myCall = function (contextObj) {
            var context = contextObj || window
            //这个时候 拿到了 
            console.log("function_this", this)
            //上面一行此时的this指的是函数本身的调用者 谁调用了myCall时 this就指向谁  因为douyu.myCall 所以这个this就指向了douyu函数
            context.fn = this
            const args = [...arguments].slice(1);//类数组转为数组
            console.log("context", context.fn)
            //要myCall前面这个函数执行  就是运行this函数
            const result = context.fn(...args)
            console.log("result输出", result)
            delete context.fn;
            return result
        }
        console.log("========执行自己跑的funtion———start========")
        douyu.myCall(huyaObj, "虎牙3_new", "虎牙4_new")
        console.log("========执行自己跑的funtion——end========")
    </script>
</body>

</html>